package com.ksl.kinglockguard.activity;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ksl.kinglockguard.R;
import com.ksl.kinglockguard.activity.base.AbstractActivity;
import com.ksl.kinglockguard.bitmap.ImageLoader;
import com.ksl.kinglockguard.data.Constants;
import com.ksl.kinglockguard.data.SharePreferenceSdkData;
import com.ksl.kinglockguard.data.UserCountHabit;
import com.ksl.kinglockguard.domain.H5List;
import com.ksl.kinglockguard.domain.H5News;
import com.ksl.kinglockguard.network.NetworkTask;
import com.ksl.kinglockguard.pay.IPayManager;
import com.ksl.kinglockguard.utils.ShortcutUtil;
import com.ksl.kinglockguard.widget.ScaleImageView;
import com.ksl.kinglockguard.widget.common.CommonDialog;
import com.ksl.kinglockguard.widget.common.CustomProgressDialog;
import com.ksl.kinglockguard.widget.common.LoadFailedView;
import com.ksl.kinglockguard.widget.common.MyTitleView;
import com.ksl.kinglockguard.widget.common.MyTitleView.MenuImageResourceListener;
import com.ksl.kinglockguard.widget.waterfall.PLA_AbsListView;
import com.ksl.kinglockguard.widget.waterfall.PLA_AbsListView.OnScrollListener;
import com.ksl.kinglockguard.widget.waterfall.PLA_AdapterView;
import com.ksl.kinglockguard.widget.waterfall.PLA_AdapterView.OnItemClickListener;
import com.ksl.kinglockguard.widget.waterfall.PLA_AdapterView.OnItemLongClickListener;
import com.ksl.kinglockguard.widget.waterfall.XListView;
import com.ksl.kinglockguard.widget.waterfall.XListView.IXListViewListener;
import com.lsk.open.core.MyLog;
import com.lsk.open.core.net.NetConnectTask;
import com.lsk.open.core.net.NetConnectTask.TaskListener;
import com.lsk.open.core.net.NetHeadUtils;
import com.lsk.open.core.serialize_cache.CacheDataManager;


public class GameListActivity extends AbstractActivity implements IXListViewListener, MenuImageResourceListener {
    private static final String TAG = "GameListActivity";
    private XListView mH5AdapterView = null;
	//h5 start from here
	private MyTitleView myTitleView;
	private Animation shakeAlphaAnim;
	private AnimationSet shakeAnimSet;
	private Animation shakeAnim;
	private H5List h5NewsList;
	private LinkedList<H5News> mH5Infos;
	CustomProgressDialog mProgressDialog;
	private ImageLoader mImageLoader;
	private H5Adapter h5Adapter = null;
	private boolean isRequesting = false;
	private boolean noMoreData = false;
	private boolean requestMax = false;
	private int maxID = -1;
	private int minID;
	private int lastItemPosition = -1;
	private View itemView;
	private int firstItem;
	private int clickedPosition;
	private Animation itemDownAnim;
    private Animation itemUpAnim;
    private LoadFailedView view_load_failed;
    private CommonDialog commonDialog;
    public final static int ON_LOAD_MORE = 0;
	public final static int ON_GET_DATA = 1;
//	public final static int ON_NO_CACHE = 2;
	public final static int GAME_NUMBER_FIXED = 10;        //每次加载10条
	public static final String FROM_H5_PAGE = "h5page";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.h5_game_activity);
        initView();
        initListener();
        initData();
        initPayEnv();
    }

    private void initPayEnv() {
        IPayManager.getInstance().initPaySdk(this);
    }

    private void initView(){
        initTitleBar();
        view_load_failed = (LoadFailedView) findViewById(R.id.view_load_failed);
        mProgressDialog = new CustomProgressDialog(this,getString(R.string.lock_loading_data));
    	mH5AdapterView = (XListView) findViewById(R.id.h5_list);
    	mH5AdapterView.setSelector(R.drawable.list_bg_selector);
    }
    
    private void initTitleBar() {
    	myTitleView = new MyTitleView(this, false);
    	myTitleView.setMenuImageResourceListener(this);
    	myTitleView.setTitleGravity(Gravity.CENTER_VERTICAL|Gravity.LEFT);
    	myTitleView.setTitle("H5游戏专区");
	}
    private void initData(){
    	mImageLoader = ImageLoader.getInstance(this);
    	mH5AdapterView.setPullLoadEnable(true);
    	mH5AdapterView.setPullRefreshEnable(false);
    	mH5AdapterView.setXListViewListener(this);
    	mImageLoader = ImageLoader.getInstance(this);
    	h5Adapter = new H5Adapter(this, mH5AdapterView);
    	mH5AdapterView.setAdapter(h5Adapter);
    	view_load_failed.setVisibility(View.GONE);
    	getH5GameList();
    }
    
    private void initListener(){
    	mH5AdapterView.setOnTouchListener(new OnTouchListener() {
			
			@SuppressLint("NewApi") @Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						clickedPosition = mH5AdapterView.pointToPosition((int)event.getX(), (int)event.getY());
						itemView = mH5AdapterView.getChildAt(clickedPosition - firstItem);
						if(itemView != null && clickedPosition >= 1)
							itemDownAnimation(itemView);
						break;
					case MotionEvent.ACTION_MOVE:
						break;
					case MotionEvent.ACTION_UP:
						if(itemView != null && clickedPosition >= 1){
							itemUpAnimation(itemView);
						}
						clickedPosition = 0;
						break;
					}
				return false;
			}
		});
    	mH5AdapterView.setOnScrollListener(new OnScrollListener() {
 			
 			@Override
 			public void onScrollStateChanged(PLA_AbsListView view, int scrollState) {
 				switch (scrollState) {
 				case OnScrollListener.SCROLL_STATE_FLING:
 					break;
 				case OnScrollListener.SCROLL_STATE_IDLE:
 					break;
 				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
 					break;
 				default:
 					break;
 				}
 			}
 				
 			@Override
 			public void onScroll(PLA_AbsListView view, int firstVisibleItem,
 					int visibleItemCount, int totalItemCount) {
 				firstItem = firstVisibleItem;
 				mH5AdapterView.setTotalItemCount(totalItemCount);
 			}
 		});
    	mH5AdapterView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(PLA_AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				MyLog.i("jyh1", "~~~~h5 position is ~~~"+position);
				position -= 1;
				if(position >= 0){
					H5News curNews = mH5Infos.get(position);

                    int engineType = curNews.getEngineType();
                    Intent intent = new Intent();
                    intent.putExtra("curNews", curNews);
                    intent.putExtra(Constants.FROM, FROM_H5_PAGE);
                    Log.d("lijc", "H5News --- curNews: " + curNews);
                    if(engineType == 1) {
                        intent.setClass(GameListActivity.this, GamePlayActivity.class);
                    } else {
                        intent.setClass(GameListActivity.this, DetailPageActivity.class);
                    }
					startActivity(intent);
				}
			}
		});
    	mH5AdapterView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(PLA_AdapterView<?> parent,
					View view, int position, long id) {
				position -= 1;
				if(position >= 0){
					final H5News curNews = mH5Infos.get(position);
					if(curNews == null)
						return false;
					if(commonDialog == null)
						commonDialog = new CommonDialog(view.getContext());
					commonDialog.setDialogTips(R.string.create_shortcut);
					commonDialog.show();
					commonDialog.setConfirmListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							//主动添加h5游戏快捷方式数据统计
							UserCountHabit.setUserCount(GameListActivity.this, UserCountHabit.H5_ACTIVE_ADD_SHORTCUT_NUM+curNews.getId());
							commonDialog.dismiss();
							ShortcutUtil.createShortCut(GameListActivity.this, curNews);
						}
					});
					commonDialog.setCancelListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							MyLog.i("jyh1", "~~~~~dont make shortcut~~~~~~");
							commonDialog.dismiss();
						}
					});
				}
				return false;
			}
		});
    }
    private void itemDownAnimation(View view){
    	/** 设置缩放动画 */   
    	itemDownAnim = new ScaleAnimation(1.0f, 0.97f, 1.0f, 0.97f,Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);  
    	//设置动画插值器 被用来修饰动画效果,定义动画的变化率   
    	itemDownAnim.setInterpolator(new DecelerateInterpolator()); 
    	itemDownAnim.setDuration(50);//设置动画持续时间   
    	itemDownAnim.setFillEnabled(true);
    	itemDownAnim.setFillAfter(true);
    	view.startAnimation(itemDownAnim);
    }
    private void itemUpAnimation(View view){
    	/** 设置缩放动画 */   
    	itemDownAnim.setFillEnabled(false);
    	itemDownAnim.setFillAfter(false);
    	itemUpAnim = new ScaleAnimation(0.97f, 1.0f, 0.97f,1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);  
    	itemUpAnim.setInterpolator(new DecelerateInterpolator()); 
    	itemUpAnim.setDuration(50);//设置动画持续时间
    	view.startAnimation(itemUpAnim);
    }

    @Override
    public void onConnectChange() {
    	// TODO Auto-generated method stub
    	super.onConnectChange();
    	if(view_load_failed.getVisibility() == View.VISIBLE){
			view_load_failed.setVisibility(View.GONE);
			mH5AdapterView.setVisibility(View.VISIBLE);
    		getH5GameList();
    	}
    }
    
    @Override
    protected void onResume() {
        super.onResume();
    }
    
    @Override
    protected void onPause() {
    	super.onPause();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        startOfflineEgretGame();
        MyLog.i("jyh1", "~~~~~~~~~~~onDestroy onDestroy ~~~~~~~~~~~");
    }
    
	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
	}

	@Override
	public void onLoadMore() {
		MyLog.i("jyh1", "~~~~~~onLoadMore~~~~~");
		if(isRequesting)
    		return;
		if (NetHeadUtils.isNetWorking(getApplicationContext())) {
			if(!noMoreData){
				minID = h5NewsList.getMinID();
	    		RequestH5GameList(minID,ON_LOAD_MORE);
	    		isRequesting = true;
			}else{
				mH5AdapterView.stopLoadMore();
				Toast.makeText(getApplicationContext(), R.string.H5_beyond_articles, Toast.LENGTH_SHORT).show();
			}
		}else{
			mH5AdapterView.stopLoadMore();
			Toast.makeText(getApplicationContext(), R.string.network_not_connected, Toast.LENGTH_SHORT).show();
		}
	}

	/**
     * 先加载本地缓存的焦点图广告，后台请求服务器焦点图广告，成功之后替换掉之前的缓存
     */
    private void getH5GameList() {
    	h5NewsList = (H5List) CacheDataManager.getListCacheOrLoadSeriaByKey(Constants.H5_LIST);
        MyLog.d("h5request","getH5GameList ----- h5NewsList: " + h5NewsList);
    	if(h5NewsList != null){
    		maxID = h5NewsList.getMaxID();
    		mH5Infos.clear();
    		mH5Infos.addAll(h5NewsList.getNewslist());
    		h5Adapter.notifyDataSetChanged();
    	}else{
    		if (NetHeadUtils.isNetWorking(getApplicationContext())) {
    			MyLog.i("jyh1", "~~~~~h5 activity request data~~~~");
    			RequestH5GameList(0,ON_GET_DATA);
                mProgressDialog.show();
    			isRequesting = true;
    			requestMax = true;
    		}else{
    			mH5AdapterView.setVisibility(View.GONE);
    			view_load_failed.setVisibility(View.VISIBLE);
    		}
    	}
    }
    
    //请求h5列表
    public void RequestH5GameList(int id,final int requestType) {
		JSONObject request = new JSONObject();
		try {
			request.put("number", GAME_NUMBER_FIXED);
            request.put("cat", Constants.ARTICLE_CAT_GAME);
            request.put("group", SharePreferenceSdkData.getUserGroup(getApplicationContext()));
			request.put("preference", SharePreferenceSdkData.getUserPreference(getApplicationContext()));
			if(requestType == ON_LOAD_MORE && id !=0)
				request.put("min_id", id);//用户上滑加载，传min_id
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
        String content = request.toString();
        Log.d("h5request", "------content: " + content);
        NetConnectTask netTask = NetworkTask.requestH5List(this, content);
		netTask.setListener(new TaskListener() {
			@Override
			public void onNoNetworking() {
				isRequesting = false;
				mProgressDialog.dismiss();
				Toast.makeText(getApplicationContext(), R.string.no_network_env , Toast.LENGTH_SHORT).show();
			}
			@Override
			public void onNetworkingError() {
				isRequesting = false; 
				mProgressDialog.dismiss();
				Toast.makeText(getApplicationContext(), R.string.network_error_env , Toast.LENGTH_SHORT).show();
			}
			@Override
			public void onPostExecute(byte[] bytes) {
				try {
					JSONObject result = new JSONObject(new String(bytes));
					String errno = result.getString("errno");
					if(result.isNull("data")){
						noMoreData = true;
						mH5AdapterView.stopLoadMore();
						isRequesting = false;
						Toast.makeText(getApplicationContext(), R.string.H5_beyond_articles, Toast.LENGTH_SHORT).show();
						return;
					}
					JSONArray dataList = null;
					if(errno.equals("200")){
						dataList = result.getJSONArray("data");
						h5NewsList = H5List.parse(dataList);
						minID = h5NewsList.getMinID();
						if(requestMax){
							CacheDataManager.deleteSeriaFile(Constants.H5_LIST);
							CacheDataManager.setListCacheAndWriteByKey(Constants.H5_LIST, h5NewsList);
//							requestMax = false;
						}
					}else{
						Toast.makeText(getApplicationContext(), R.string.network_error_env , Toast.LENGTH_SHORT).show();
						return;
					}
					if (dataList.length() < GAME_NUMBER_FIXED)
						noMoreData = true;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				isRequesting = false;
				setData();
				mProgressDialog.dismiss();
			}
		});

	}
    
    private void setData(){
    	mH5AdapterView.stopLoadMore();
        h5Adapter.addItemLast(h5NewsList.getNewslist());
        h5Adapter.notifyDataSetChanged();
    }
	
    private void flipUpAnim(View view,Context mContext){
    	shakeAlphaAnim = getReverseAlphaAnimation();
        shakeAnimSet = new AnimationSet(false);
        shakeAnimSet.addAnimation(shakeAlphaAnim);
        shakeAnim = AnimationUtils.loadAnimation(mContext, R.anim.shake_y);
        shakeAnimSet.addAnimation(shakeAnim);
        view.startAnimation(shakeAnimSet);
    }
    private Animation getReverseAlphaAnimation() {  
    	//实例化 AlphaAnimation 主要是改变透明度  
    	//透明度 从 1-不透明 0-完全透明   
    	Animation animation = new AlphaAnimation(0.0f, 1.0f);  
    	//设置动画插值器 被用来修饰动画效果,定义动画的变化率   
    	animation.setInterpolator(new DecelerateInterpolator());  
    	//设置动画执行时间  
    	animation.setDuration(500);  
    	return animation;  
    } 
    
	public class H5Adapter extends BaseAdapter {
        private Context mContext;

        public H5Adapter(Context context, XListView xListView) {
            mContext = context;
            mH5Infos = new LinkedList<H5News>();
        }

        @SuppressWarnings("null")
		@SuppressLint("NewApi") @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder;
            final H5News itemNews = mH5Infos.get(position);
            if (convertView == null) {
                LayoutInflater layoutInflator = LayoutInflater.from(parent.getContext());
                convertView = layoutInflator.inflate(R.layout.h5_infos_list, null);
                holder = new ViewHolder();
                holder.itemImage = (ScaleImageView) convertView.findViewById(R.id.h5_pic);
                holder.contentView = (TextView) convertView.findViewById(R.id.h5_title);
                holder.summary = (TextView) convertView.findViewById(R.id.h5_summary);
                holder.playersNumber = (TextView) convertView.findViewById(R.id.players_number);
                holder.gameTag = (ImageView) convertView.findViewById(R.id.game_tag);
                holder.shortcutTag = (ImageView) convertView.findViewById(R.id.produce_shortcut);
                convertView.setTag(holder);
            }

            holder = (ViewHolder) convertView.getTag(); 
            holder.itemImage.setImageWidth(200);
            float ratio = itemNews.getMiddleImageHeight()/(float)itemNews.getMiddleImageWidth();
            holder.itemImage.setImageHeight((int)(200*ratio));
            holder.contentView.setText(itemNews.getTitle());
            if(itemNews.getSummary().isEmpty())
            	holder.summary.setVisibility(View.GONE);
            else
            	holder.summary.setText(itemNews.getSummary());
            holder.playersNumber.setText(itemNews.getPlayersNumber()+"人在玩");
            holder.itemImage.setImageResource(R.drawable.zwt_pic);
            if(itemNews.getGameFlag() == H5News.GAME_FLAG_HOT)
            	holder.gameTag.setImageResource(R.drawable.jiaobiao_gamelist_hot);
            else if(itemNews.getGameFlag() == H5News.GAME_FLAG_NEW)
            	holder.gameTag.setImageResource(R.drawable.jiaobiao_gamelist_new);
            else
            	holder.gameTag.setImageBitmap(null);
            MyLog.i("jyh1", "~~~~~gameTag is~~~"+itemNews.getGameFlag()+"~~~pos is~~~"+position);
            mImageLoader.DisplayImage(itemNews.getMiddleImageUrl(), holder.itemImage, false,ImageLoader.LOCK_H5_PICTURE);
            if(position > lastItemPosition){
            	flipUpAnim(convertView, mContext);
            	lastItemPosition = position;
            }
            holder.shortcutTag.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(commonDialog == null)
						commonDialog = new CommonDialog(mContext);
					commonDialog.setDialogTips(R.string.create_shortcut);
					commonDialog.show();
					commonDialog.setConfirmListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							//主动添加h5游戏快捷方式数据统计
							UserCountHabit.setUserCount(GameListActivity.this, UserCountHabit.H5_ACTIVE_ADD_SHORTCUT_NUM+itemNews.getId());
							commonDialog.dismiss();
							ShortcutUtil.createShortCut(mContext, itemNews);
						}
					});
					commonDialog.setCancelListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							MyLog.i("jyh1", "~~~~~dont make shortcut~~~~~~");
							commonDialog.dismiss();
						}
					});
				}
			});
            return convertView;
        }

        class ViewHolder {
            ScaleImageView itemImage;
            ImageView gameTag;
            ImageView shortcutTag;
            TextView contentView;
            TextView summary;
            TextView playersNumber;
        }

        @Override
        public int getCount() {
            return mH5Infos.size();
        }

        @Override
        public Object getItem(int arg0) {
            return mH5Infos.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return 0;
        }

        public void addItemLast(List<H5News> datas) {
        	if(requestMax){
        		mH5Infos.clear();
        		requestMax = false;
        	}
        	mH5Infos.addAll(datas);
        }

        public void addItemTop(List<H5News> datas) {
            for (H5News info : datas) {
            	mH5Infos.addFirst(info);
            }
        }
    }

	@Override
	public String getUserHabitKey() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setMenuImageResource(ImageView menu_img, int id) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setImageBtnGray(ImageView menu_img, int id) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setImageBtnNormal(ImageView menu_img, int id) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void goBackPreviousPage(boolean parentPage) {
		// TODO Auto-generated method stub
		this.finish();
	}
}// end of class
